package mysql

import (
	"bluebell/models"
	"go.uber.org/zap"
)

func CreateComment(c *models.Comment) error {
	// 直接执行SQL（假设已经在前置逻辑中验证了c.PostID和c.UserID是有效的int64）
	sqlStr := `INSERT INTO comment (post_id, user_id, content, create_time) 
	           VALUES (?, ?, ?, ?)`

	_, err := db.Exec(sqlStr, c.PostID, c.UserID, c.Content, c.CreateTime)
	if err != nil {
		zap.L().Error("create comment failed", zap.Error(err))
		return err
	}

	// 简单更新计数（如果失败只记录错误，不中断流程）
	if err := IncrementCommentCount(c.PostID); err != nil {
		zap.L().Error("increment comment count failed",
			zap.Int64("post_id", c.PostID),
			zap.Error(err))
		// 注意：这里不返回错误，因为主操作已完成
	}

	return nil
}

func GetCommentList(postID, page, size int64) ([]*models.Comment, error) {
	var comments []*models.Comment
	sqlStr := `SELECT comment_id, post_id, user_id, content, create_time 
               FROM comment 
               WHERE post_id = ? 
               ORDER BY create_time DESC 
               LIMIT ?, ?`
	err := db.Select(&comments, sqlStr, postID, (page-1)*size, size)
	if err != nil {
		zap.L().Error("get comment list failed", zap.Error(err))
		return nil, err
	}
	return comments, nil
}
